package com.xiaoyu.lanling.widget.player;

import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.transition.TransitionManager;

import com.facebook.drawee.view.SimpleDraweeView;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.model.VideoOptionModel;
import com.shuyu.gsyvideoplayer.utils.CommonUtil;
import com.shuyu.gsyvideoplayer.utils.Debuger;
import com.shuyu.gsyvideoplayer.video.NormalGSYVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYBaseVideoPlayer;
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer;
import com.xiaoyu.base.image.ImageLoadInfo;
import com.xiaoyu.base.utils.RxUtils;
import com.xiaoyu.lanling.R;
import com.xiaoyu.lanling.feature.chat.model.message.ChatMessageReceiveSendBaseItem;
import com.xiaoyu.lanling.feature.chat.model.message.ChatMessageReceiveVideoItem;
import com.xiaoyu.lanling.feature.chat.model.message.ChatMessageSendVideoItem;
import com.xiaoyu.lanling.media.image.ImageLoadParam;
import com.xiaoyu.lanling.media.image.ImageViewUtil;
import com.xiaoyu.lanling.util.ViewTagUtil;
import com.xiaoyu.lib_av.manager.CallManager;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import in.srain.cube.util.LocalDisplay;
import in.srain.cube.util.TimeUtils;
import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import moe.codeest.enviews.ENDownloadView;
import tv.danmaku.ijk.media.player.IjkMediaPlayer;

import static com.shuyu.gsyvideoplayer.utils.CommonUtil.getActionBarHeight;
import static com.shuyu.gsyvideoplayer.utils.CommonUtil.getStatusBarHeight;
import static com.shuyu.gsyvideoplayer.utils.CommonUtil.hideNavKey;
import static com.shuyu.gsyvideoplayer.utils.CommonUtil.hideSupportActionBar;
import static com.shuyu.gsyvideoplayer.utils.CommonUtil.showNavKey;
import static com.shuyu.gsyvideoplayer.utils.CommonUtil.showSupportActionBar;
import static com.xiaoyu.lanling.feature.chat.viewholder.messageclick.ChatMessageVideoItemClickHandler.receiveVideoOnLongClickListener;
import static com.xiaoyu.lanling.feature.chat.viewholder.messageclick.ChatMessageVideoItemClickHandler.sendVideoOnLongClickListener;

public class MessageVideoPlayer extends NormalGSYVideoPlayer {

    private SimpleDraweeView mCoverImage;
    private TextView mDurationView;
    private ImageButton mBottomStartView;

    private String mThumbUrl;
    private ImageLoadInfo mImageLoadInfo;
    private Disposable mClickToggleDisposable;

    public MessageVideoPlayer(final Context context, final Boolean fullFlag) {
        super(context, fullFlag);
    }

    public MessageVideoPlayer(final Context context) {
        super(context);
    }

    public MessageVideoPlayer(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void init(final Context context) {
        super.init(context);
        Debuger.enable();
        mCoverImage = findViewById(R.id.thumbImage);
        mDurationView = findViewById(R.id.duration);
        mBottomStartView = findViewById(R.id.bottom_start);

        mCurrentTimeTextView.setText("OO:OO");
        mTotalTimeTextView.setText("OO:OO");

        if (mBackButton != null) {
            mBackButton.setVisibility(isIfCurrentIsFullscreen() ? VISIBLE : GONE);
        }
        if (mThumbImageViewLayout != null && (mCurrentState == -1 || mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR)) {
            mThumbImageViewLayout.setVisibility(VISIBLE);
        }
        if (mBottomStartView != null) {
            mBottomStartView.setOnClickListener(this);
        }

        setViewShowState(mBottomProgressBar, GONE);
        setViewShowState(mFullscreenButton, GONE);
        setViewShowState(mLockScreen, GONE);
        setViewShowState(mSmallClose, GONE);

        enableAccurateSeek();
    }

    private void enableAccurateSeek() {
        VideoOptionModel videoOptionModel = new VideoOptionModel(IjkMediaPlayer.OPT_CATEGORY_PLAYER, "enable-accurate-seek", 1);
        List<VideoOptionModel> list = new ArrayList<>();
        list.add(videoOptionModel);
        GSYVideoManager.instance().setOptionModelList(list);
    }

    @Override
    public int getLayoutId() {
        return R.layout.view_chat_message_video_player;
    }

    public void setDuration(int duration) {
        mDurationView.setText(TimeUtils.secondsToClockText(duration));
    }

    public void loadCoverImage(final String thumbUrl, final int width, final int height) {
        this.mThumbUrl = thumbUrl;
        this.mImageLoadInfo = new ImageLoadInfo(width, height);
        ImageViewUtil.INSTANCE.loadImage(mCoverImage, ImageLoadParam.newBuilder().setUrl(thumbUrl).setWidth(width).setHeight(height).build());
    }

    public <T> void bindReceiveVideoItemViewAndDataForLongClick(T data) {
        if (mThumbImageViewLayout != null) {
            mThumbImageViewLayout.setOnLongClickListener(receiveVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mThumbImageViewLayout, data);
        }
        if (mTextureViewContainer != null) {
            mTextureViewContainer.setOnLongClickListener(receiveVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mTextureViewContainer, data);
        }
        if (mStartButton != null) {
            mStartButton.setOnLongClickListener(receiveVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mStartButton, data);
        }
    }

    public <T> void bindSendVideoItemViewAndDataForLongClick(T data) {
        if (mThumbImageViewLayout != null) {
            mThumbImageViewLayout.setOnLongClickListener(sendVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mThumbImageViewLayout, data);
        }
        if (mTextureViewContainer != null) {
            mTextureViewContainer.setOnLongClickListener(sendVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mTextureViewContainer, data);
        }
        if (mStartButton != null) {
            mStartButton.setOnLongClickListener(sendVideoOnLongClickListener);
            ViewTagUtil.setViewTagForClick(mStartButton, data);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        RxUtils.disposable(mClickToggleDisposable);
        unListenerNetWorkState();
    }

    /**
     * 定义开始按键显示
     */
    protected void updateStartImage() {
        if (mStartButton instanceof ImageView) {
            ImageView imageView = (ImageView) mStartButton;
            switch (mCurrentState) {
                case CURRENT_STATE_NORMAL:
                case CURRENT_STATE_ERROR:
                case CURRENT_STATE_PAUSE:
                case CURRENT_STATE_AUTO_COMPLETE:
                    imageView.setImageResource(R.drawable.chat_video_play_icon);
                    imageView.setVisibility(VISIBLE);
                    break;
                default:
                    imageView.setVisibility(GONE);
            }
        }
        if (mBottomStartView != null) {
            ImageButton imageButton = mBottomStartView;
            switch (mCurrentState) {
                case CURRENT_STATE_PLAYING:
                    imageButton.setImageResource(R.drawable.player_pause_icon);
                    break;
                default:
                    imageButton.setImageResource(R.drawable.player_resume_icon);
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (mHideKey && mIfCurrentIsFullscreen) {
            hideNavKey(mContext);
        }
        if (i == R.id.start) {
            clickStartIcon();
        } else if (i == R.id.bottom_start) {
            clickBottomStartIcon();
        } else if (i == R.id.back) {
            GSYVideoManager.backFromWindowFull(getContext());
        } else if (i == R.id.surface_container && mCurrentState == CURRENT_STATE_ERROR) {
            if (mVideoAllCallBack != null) {
                Debuger.printfLog("onClickStartError");
                mVideoAllCallBack.onClickStartError(mOriginUrl, mTitle, this);
            }
            prepareVideo();
        } else if (i == R.id.thumb) {
            if (!mThumbPlay) {
                return;
            }
            if (isIfCurrentIsFullscreen()) {
                changeUIForToggle();
            } else {
                clickStartIcon();
            }
        } else if (i == R.id.surface_container) {
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                if (mIfCurrentIsFullscreen) {
                    Debuger.printfLog("onClickBlankFullscreen");
                    mVideoAllCallBack.onClickBlankFullscreen(mOriginUrl, mTitle, this);
                } else {
                    Debuger.printfLog("onClickBlank");
                    mVideoAllCallBack.onClickBlank(mOriginUrl, mTitle, this);
                }
            }
            changeUIForToggle();
        }
    }

    /**
     * 点击触摸显示和隐藏逻辑
     */
    @Override
    protected void onClickUiToggle() {
        // empty
    }

    @Override
    protected void touchDoubleUp() {
        // empty
    }

    @Override
    protected void clickStartIcon() {
        if (TextUtils.isEmpty(mUrl)) {
            Debuger.printfError("********" + getResources().getString(R.string.no_url));
            return;
        }
        if (isIfCurrentIsFullscreen()) {
            switch (mCurrentState) {
                case CURRENT_STATE_NORMAL:
                case CURRENT_STATE_ERROR:
                case CURRENT_STATE_AUTO_COMPLETE:
                    startButtonLogic();
                    break;
                case CURRENT_STATE_PAUSE:
                    if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                        if (mIfCurrentIsFullscreen) {
                            Debuger.printfLog("onClickResumeFullscreen");
                            mVideoAllCallBack.onClickResumeFullscreen(mOriginUrl, mTitle, this);
                        } else {
                            Debuger.printfLog("onClickResume");
                            mVideoAllCallBack.onClickResume(mOriginUrl, mTitle, this);
                        }
                    }

                    if (!mHadPlay && !mStartAfterPrepared) {
                        startAfterPrepared();
                    }

                    try {
                        getGSYVideoManager().start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    setStateAndUi(CURRENT_STATE_PLAYING);
                    break;
                case CURRENT_STATE_PLAYING:
                    try {
                        onVideoPause();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    setStateAndUi(CURRENT_STATE_PAUSE);
                    if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                        if (mIfCurrentIsFullscreen) {
                            Debuger.printfLog("onClickStopFullscreen");
                            mVideoAllCallBack.onClickStopFullscreen(mOriginUrl, mTitle, this);
                        } else {
                            Debuger.printfLog("onClickStop");
                            mVideoAllCallBack.onClickStop(mOriginUrl, mTitle, this);
                        }
                    }
                    break;
            }
        } else {
            startButtonLogic();
            startWindowFullscreen(getContext(), false, true);
        }
    }

    private void clickBottomStartIcon() {
        if (TextUtils.isEmpty(mUrl)) {
            Debuger.printfError("********" + getResources().getString(R.string.no_url));
            return;
        }
        if (mCurrentState == CURRENT_STATE_NORMAL || mCurrentState == CURRENT_STATE_ERROR) {
            if (isShowNetConfirm()) {
                showWifiDialog();
                return;
            }
            startButtonLogic();
        } else if (mCurrentState == CURRENT_STATE_PLAYING) {
            try {
                onVideoPause();
            } catch (Exception e) {
                e.printStackTrace();
            }
            setStateAndUi(CURRENT_STATE_PAUSE);
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                if (mIfCurrentIsFullscreen) {
                    Debuger.printfLog("onClickStopFullscreen");
                    mVideoAllCallBack.onClickStopFullscreen(mOriginUrl, mTitle, this);
                } else {
                    Debuger.printfLog("onClickStop");
                    mVideoAllCallBack.onClickStop(mOriginUrl, mTitle, this);
                }
            }
        } else if (mCurrentState == CURRENT_STATE_PAUSE) {
            if (mVideoAllCallBack != null && isCurrentMediaListener()) {
                if (mIfCurrentIsFullscreen) {
                    Debuger.printfLog("onClickResumeFullscreen");
                    mVideoAllCallBack.onClickResumeFullscreen(mOriginUrl, mTitle, this);
                } else {
                    Debuger.printfLog("onClickResume");
                    mVideoAllCallBack.onClickResume(mOriginUrl, mTitle, this);
                }
            }

            if (!mHadPlay && !mStartAfterPrepared) {
                startAfterPrepared();
            }

            try {
                getGSYVideoManager().start();
            } catch (Exception e) {
                e.printStackTrace();
            }
            setStateAndUi(CURRENT_STATE_PLAYING);
        } else if (mCurrentState == CURRENT_STATE_AUTO_COMPLETE) {
            startButtonLogic();
        }
    }

    /**
     * 利用window层播放全屏效果
     *
     * @param context
     * @param actionBar 是否有actionBar，有的话需要隐藏
     * @param statusBar 是否有状态bar，有的话需要隐藏
     */
    @SuppressWarnings("ResourceType, unchecked")
    public GSYBaseVideoPlayer startWindowFullscreen(final Context context, final boolean actionBar, final boolean statusBar) {
        int height = (int) (LocalDisplay.SCREEN_WIDTH_PIXELS * 1F / mImageLoadInfo.getRatio());

        mSystemUiVisibility = ((Activity) context).getWindow().getDecorView().getSystemUiVisibility();

        hideSupportActionBar(context, actionBar, statusBar);

        if (mHideKey) {
            hideNavKey(context);
        }

        this.mActionBar = actionBar;
        this.mStatusBar = statusBar;

        mListItemRect = new int[2];
        mListItemSize = new int[2];

        final ViewGroup vp = getViewGroup();
        removeVideo(vp, getFullId());

        //处理暂停的逻辑
        pauseFullCoverLogic();

        if (mTextureViewContainer.getChildCount() > 0) {
            mTextureViewContainer.removeAllViews();
        }

        saveLocationStatus(context, statusBar, actionBar);

        //切换时关闭非全屏定时器
        cancelProgressTimer();

        boolean hadNewConstructor = true;

        try {
            MessageVideoPlayer.this.getClass().getConstructor(Context.class, Boolean.class);
        } catch (Exception e) {
            hadNewConstructor = false;
        }

        try {
            //通过被重载的不同构造器来选择
            Constructor<MessageVideoPlayer> constructor;
            final MessageVideoPlayer gsyVideoPlayer;
            if (hadNewConstructor) {
                constructor = (Constructor<MessageVideoPlayer>) getClass().getConstructor(Context.class, Boolean.class);
                gsyVideoPlayer = constructor.newInstance(getActivityContext(), true);
            } else {
                constructor = (Constructor<MessageVideoPlayer>) getClass().getConstructor(Context.class);
                gsyVideoPlayer = constructor.newInstance(getActivityContext());
            }

            gsyVideoPlayer.setId(getFullId());
            gsyVideoPlayer.setIfCurrentIsFullscreen(true);
            gsyVideoPlayer.setVideoAllCallBack(mVideoAllCallBack);

            cloneParams(this, gsyVideoPlayer);

            final LayoutParams lpParent = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            final FrameLayout frameLayout = new FrameLayout(context);

            if (mShowFullAnimation) {
                LayoutParams lp = new LayoutParams(getWidth(), getHeight());
                lp.setMargins(mListItemRect[0], mListItemRect[1], 0, 0);
                frameLayout.addView(gsyVideoPlayer, lp);
                vp.addView(frameLayout, lpParent);
                post(() -> {
                    TransitionManager.beginDelayedTransition(vp);
                    resolveFullVideoShow(context, gsyVideoPlayer, frameLayout);
                });
            } else {
                LayoutParams lp = new LayoutParams(getWidth(), getHeight());
                frameLayout.addView(gsyVideoPlayer, lp);
                vp.addView(frameLayout, lpParent);
                gsyVideoPlayer.setVisibility(INVISIBLE);
                frameLayout.setVisibility(INVISIBLE);
                resolveFullVideoShow(context, gsyVideoPlayer, frameLayout);
            }

            gsyVideoPlayer.addTextureView();
            gsyVideoPlayer.startProgressTimer();
            gsyVideoPlayer.loadCoverImage(mThumbUrl, LocalDisplay.SCREEN_WIDTH_PIXELS, height);

            ChatMessageReceiveSendBaseItem baseItem = ViewTagUtil.getTag(mThumbImageViewLayout, ChatMessageReceiveSendBaseItem.class);
            if (baseItem instanceof ChatMessageSendVideoItem) {
                gsyVideoPlayer.bindSendVideoItemViewAndDataForLongClick(baseItem);
            } else if (baseItem instanceof ChatMessageReceiveVideoItem) {
                gsyVideoPlayer.bindReceiveVideoItemViewAndDataForLongClick(baseItem);
            }

            getGSYVideoManager().setLastListener(this);
            getGSYVideoManager().setListener(gsyVideoPlayer);

            checkoutState();
            return gsyVideoPlayer;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void cloneParams(final GSYBaseVideoPlayer from, final GSYBaseVideoPlayer to) {
        super.cloneParams(from, to);
        to.setThumbPlay(mThumbPlay);
    }

    private ViewGroup getViewGroup() {
        return (ViewGroup) (CommonUtil.scanForActivity(getContext())).findViewById(Window.ID_ANDROID_CONTENT);
    }

    /**
     * 保存大小和状态
     */
    private void saveLocationStatus(Context context, boolean statusBar, boolean actionBar) {
        getLocationOnScreen(mListItemRect);
        int statusBarH = getStatusBarHeight(context);
        int actionBerH = getActionBarHeight((Activity) context);
        if (statusBar) {
            mListItemRect[1] = mListItemRect[1] - statusBarH;
        }
        if (actionBar) {
            mListItemRect[1] = mListItemRect[1] - actionBerH;
        }
        mListItemSize[0] = getWidth();
        mListItemSize[1] = getHeight();
    }

    /**
     * 全屏的暂停的时候返回页面不黑色
     */
    private void pauseFullCoverLogic() {
        if (mCurrentState == GSYVideoPlayer.CURRENT_STATE_PAUSE && mTextureView != null
                && (mFullPauseBitmap == null || mFullPauseBitmap.isRecycled()) && mShowPauseCover) {
            try {
                initCover();
            } catch (Exception e) {
                e.printStackTrace();
                mFullPauseBitmap = null;
            }
        }
    }

    /**
     * 移除没用的
     */
    private void removeVideo(ViewGroup vp, int id) {
        View old = vp.findViewById(id);
        if (old != null) {
            if (old.getParent() != null) {
                ViewGroup viewGroup = (ViewGroup) old.getParent();
                vp.removeView(viewGroup);
            }
        }
    }

    @Override
    protected void resolveFullVideoShow(Context context, GSYBaseVideoPlayer gsyVideoPlayer, FrameLayout frameLayout) {
        super.resolveFullVideoShow(context, gsyVideoPlayer, frameLayout);
        boolean isInternalCalling = CallManager.Companion.getInstance().isCalling();
        if (isInternalCalling) {
            mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        } else {
            mAudioManager.requestAudioFocus(onAudioFocusChangeListener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
        }
        setViewShowState(mDurationView, GONE);
    }

    /**
     * 恢复
     */
    protected void resolveNormalVideoShow(View oldF, ViewGroup vp, GSYVideoPlayer gsyVideoPlayer) {

        if (oldF != null && oldF.getParent() != null) {
            ViewGroup viewGroup = (ViewGroup) oldF.getParent();
            vp.removeView(viewGroup);
        }
        mCurrentState = getGSYVideoManager().getLastState();
        if (gsyVideoPlayer != null) {
            cloneParams(gsyVideoPlayer, this);
        }
        getGSYVideoManager().setListener(getGSYVideoManager().lastListener());
        getGSYVideoManager().setLastListener(null);
        setStateAndUi(mCurrentState);
        addTextureView();
        mSaveChangeViewTIme = System.currentTimeMillis();
        if (mVideoAllCallBack != null) {
            Debuger.printfError("onQuitFullscreen");
            mVideoAllCallBack.onQuitFullscreen(mOriginUrl, mTitle, this);
        }
        mIfCurrentIsFullscreen = false;
        if (mHideKey) {
            showNavKey(mContext, mSystemUiVisibility);
        }
        showSupportActionBar(mContext, mActionBar, mStatusBar);
        if (getFullscreenButton() != null) {
            getFullscreenButton().setImageResource(getEnlargeImageRes());
        }
        mAudioManager.abandonAudioFocus(onAudioFocusChangeListener);
        setStateAndUi(CURRENT_STATE_NORMAL);
        setViewShowState(mDurationView, VISIBLE);
    }

    /**
     * 退出window层播放全屏效果
     */
    @SuppressWarnings("ResourceType")
    protected void clearFullscreenLayout() {
        mIfCurrentIsFullscreen = false;
        int delay = 0;
        if (mOrientationUtils != null) {
            delay = mOrientationUtils.backToProtVideo();
            mOrientationUtils.setEnable(false);
            if (mOrientationUtils != null) {
                mOrientationUtils.releaseListener();
                mOrientationUtils = null;
            }
        }

        if (!mShowFullAnimation) {
            delay = 0;
        }

        final ViewGroup vp = getViewGroup();
        final View oldF = vp.findViewById(getFullId());
        if (oldF != null) {
            //此处fix bug#265，推出全屏的时候，虚拟按键问题
            MessageVideoPlayer gsyVideoPlayer = (MessageVideoPlayer) oldF;
            gsyVideoPlayer.mIfCurrentIsFullscreen = false;
        }

        backToNormal();
    }

    /**
     * 回到正常效果
     */
    @SuppressWarnings("ResourceType")
    protected void backToNormal() {

        final ViewGroup vp = getViewGroup();

        final View oldF = vp.findViewById(getFullId());
        final MessageVideoPlayer gsyVideoPlayer;
        if (oldF != null) {
            gsyVideoPlayer = (MessageVideoPlayer) oldF;
            //如果暂停了
            pauseFullBackCoverLogic(gsyVideoPlayer);
            if (mShowFullAnimation) {
                TransitionManager.beginDelayedTransition(vp);

                LayoutParams lp = (LayoutParams) gsyVideoPlayer.getLayoutParams();
                lp.setMargins(mListItemRect[0], mListItemRect[1], 0, 0);
                lp.width = mListItemSize[0];
                lp.height = mListItemSize[1];
                //注意配置回来，不然动画效果会不对
                lp.gravity = Gravity.NO_GRAVITY;
                gsyVideoPlayer.setLayoutParams(lp);

                postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        resolveNormalVideoShow(oldF, vp, gsyVideoPlayer);
                    }
                }, 400);
            } else {
                resolveNormalVideoShow(oldF, vp, gsyVideoPlayer);
            }
        } else {
            resolveNormalVideoShow(null, vp, null);
        }
    }

    /**
     * 全屏的暂停返回的时候返回页面不黑色
     */
    private void pauseFullBackCoverLogic(MessageVideoPlayer gsyVideoPlayer) {
        //如果是暂停状态
        if (gsyVideoPlayer.mCurrentState == GSYVideoPlayer.CURRENT_STATE_PAUSE
                && gsyVideoPlayer.mTextureView != null && mShowPauseCover) {
            //全屏的位图还在，说明没播放，直接用原来的
            if (gsyVideoPlayer.mFullPauseBitmap != null
                    && !gsyVideoPlayer.mFullPauseBitmap.isRecycled() && mShowPauseCover) {
                mFullPauseBitmap = gsyVideoPlayer.mFullPauseBitmap;
            } else if (mShowPauseCover) {
                //不在了说明已经播放过，还是暂停的话，我们拿回来就好
                try {
                    initCover();
                } catch (Exception e) {
                    e.printStackTrace();
                    mFullPauseBitmap = null;
                }
            }
        }
    }

    @Override
    protected void hideAllWidget() {
        // empty
    }

    @Override
    protected void changeUiToNormal() {
        Debuger.printfLog("changeUiToNormal");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, GONE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, GONE);
        updateStartImage();

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }

    @Override
    protected void changeUiToPreparingShow() {
        Debuger.printfLog("changeUiToPreparingShow");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, getVisibilityWhenFullscreenChange());
        setViewShowState(mThumbImageViewLayout, GONE);
        setViewShowState(mBottomProgressBar, GONE);
        updateStartImage();

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ENDownloadView enDownloadView = (ENDownloadView) mLoadingProgressBar;
            if (enDownloadView.getCurrentState() == ENDownloadView.STATE_PRE) {
                ((ENDownloadView) mLoadingProgressBar).start();
            }
        }
    }

    @Override
    protected void changeUiToPlayingShow() {
        super.changeUiToPlayingShow();
        Debuger.printfLog("changeUiToPlayingShow");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, GONE);
        setViewShowState(mThumbImageViewLayout, GONE);
        setViewShowState(mBottomProgressBar, GONE);
        updateStartImage();

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }

    @Override
    protected void changeUiToPauseShow() {
        Debuger.printfLog("changeUiToPauseShow");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, GONE);
        setViewShowState(mThumbImageViewLayout, GONE);
        setViewShowState(mBottomProgressBar, GONE);
        updateStartImage();
        updatePauseCover();

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
    }

    @Override
    protected void changeUiToPlayingBufferingShow() {
        Debuger.printfLog("changeUiToPlayingBufferingShow");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, getVisibilityWhenFullscreenChange());
        setViewShowState(mThumbImageViewLayout, GONE);
        setViewShowState(mBottomProgressBar, GONE);
        updateStartImage();

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ENDownloadView enDownloadView = (ENDownloadView) mLoadingProgressBar;
            if (enDownloadView.getCurrentState() == ENDownloadView.STATE_PRE) {
                ((ENDownloadView) mLoadingProgressBar).start();
            }
        }
    }

    @Override
    protected void changeUiToCompleteShow() {
        Debuger.printfLog("changeUiToCompleteShow");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, GONE);
        setViewShowState(mThumbImageViewLayout, VISIBLE);
        setViewShowState(mBottomProgressBar, GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
        updateStartImage();
    }

    @Override
    protected void changeUiToError() {
        Debuger.printfLog("changeUiToError");

        if (mClickToggleDisposable == null || mClickToggleDisposable.isDisposed()) {
            setViewShowState(mTopContainer, GONE);
            setViewShowState(mBottomContainer, GONE);
        }
        setViewShowState(mLoadingProgressBar, GONE);
        setViewShowState(mThumbImageViewLayout, GONE);
        setViewShowState(mBottomProgressBar, GONE);

        if (mLoadingProgressBar instanceof ENDownloadView) {
            ((ENDownloadView) mLoadingProgressBar).reset();
        }
        updateStartImage();
    }

    protected void changeUiToPrepareingClear() {
    }

    protected void changeUiToPlayingClear() {
    }

    protected void changeUiToPauseClear() {
    }

    protected void changeUiToPlayingBufferingClear() {
    }

    protected void changeUiToClear() {
    }

    protected void changeUiToCompleteClear() {
    }

    private int getVisibilityWhenFullscreenChange() {
        return isIfCurrentIsFullscreen() ? VISIBLE : INVISIBLE;
    }

    private void changeUIForToggle() {
        setStartButtonVisibilityForToggle(mStartButton);
        setViewShowState(mTopContainer, getVisibilityForToggle(mTopContainer));
        setViewShowState(mBottomContainer, getVisibilityForToggle(mBottomContainer));
        RxUtils.disposable(mClickToggleDisposable);
        mClickToggleDisposable = Single.timer(5000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(time -> {
                    setViewShowState(mStartButton, canGoneStartButton() ? GONE : VISIBLE);
                    setViewShowState(mTopContainer, GONE);
                    setViewShowState(mBottomContainer, GONE);
                }, Throwable::printStackTrace);
    }

    private int getVisibilityForToggle(View view) {
        if (!isIfCurrentIsFullscreen()) {
            return GONE;
        }
        if (view.getVisibility() == VISIBLE) {
            return GONE;
        } else {
            return VISIBLE;
        }
    }

    private boolean canGoneStartButton() {
        return mCurrentState != CURRENT_STATE_NORMAL && mCurrentState != CURRENT_STATE_ERROR && mCurrentState != CURRENT_STATE_AUTO_COMPLETE;
    }

    private void setStartButtonVisibilityForToggle(View view) {
        if (!isIfCurrentIsFullscreen()) {
            setViewShowState(view, VISIBLE);
        }

        int bottomVisibility = getVisibilityForToggle(mBottomContainer);

        if (view.getVisibility() == VISIBLE) {
            if (canGoneStartButton()) {
                setViewShowState(view, bottomVisibility);
            }
        } else {
            if (mCurrentState == CURRENT_STATE_PAUSE) {
                setViewShowState(view, bottomVisibility);
            }
        }
    }
}
